package com.iot.ic.modules.web;

import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.iot.ic.common.web.BaseController;
import com.iot.ic.modules.model.Trade;
import com.iot.ic.modules.model.User;
import com.iot.ic.modules.service.PatientCaseService;
import com.iot.ic.modules.service.TradeService;
import com.iot.ic.modules.service.UserService;

@Controller
@RequestMapping("/trade")
public class TradeController extends BaseController {
	private final String APP_ID = "";
	private final String APP_PRIVATE_KEY = "";
	private final String ALIPAY_PUBLIC_KEY = "";

	@Autowired
	private UserService userService;
	@Autowired
	private TradeService tradeService;
	@Autowired
	private PatientCaseService patientCaseService;
	/**
	 * 调试：http://openapi.alipaydev.com/gateway.do
	 * 线上：https://openapi.alipay.com/gateway.do
	 */
	private String serverUrl = "https://openapi.alipaydev.com/gateway.do";
	private String notifyUrl = "https://home.halumm.net/iotic/trade/notifyUrl.html";
	private String charset = "UTF-8";
	private String signType = "RSA2";

	/**
	 * 生成APP支付订单信息示例
	 * 
	 * @return
	 */
	@RequestMapping("/creatTrader")
	@ResponseBody
	public Map<String, Object> creatTrader(Integer pId, Integer drId, Double amount) {
		if(pId==null){
			return packInfo(false, "参数为空","pId");
		}
		if(drId==null){
			return packInfo(false, "参数为空","drId");
		}

		long currtime = System.currentTimeMillis() / 1000l;
		AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, APP_ID, APP_PRIVATE_KEY, "json", charset,
				ALIPAY_PUBLIC_KEY, signType);
		// 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
		// SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		model.setBody("病例诊断金");
		model.setSubject("诊费");
		model.setOutTradeNo(String.valueOf(currtime));
		model.setTimeoutExpress("30m");
		model.setTotalAmount(String.valueOf(amount));
		model.setProductCode("QUICK_MSECURITY_PAY");
		request.setBizModel(model);
		request.setNotifyUrl(notifyUrl);
		try {
			// 这里和普通的接口调用不同，使用的是sdkExecute, 可以直接给客户端请求，无需再做处理。
//			AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
//			System.out.println(response.getBody());
			User drUser = userService.findById(drId , 1);
			User pUser = userService.findById(pId , 0);
			if(drUser==null||pUser==null){
				return packInfo(false, "病人或医生不存在");
			}
			Trade trade = new Trade();
			trade.setAddtime(new Date(currtime * 1000l));
			trade.setTradeNo(String.valueOf(currtime));
			trade.setAmount(amount);
			trade.setPayer(pUser);
			trade.setPayee(drUser);
			trade.setStatus("0");
			trade.setTradeName(pUser.getTrueName() +"->诊金->"+drUser.getTrueName());
			return packSaveInfo(tradeService.saveOrUpdateObject(trade));
		} catch (AlipayApiException e) {
			e.printStackTrace();
			return packInfo(false, e.getMessage(),"创建支付宝订单失败");
		}catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}

	@RequestMapping("/notifyUrl")
	@ResponseBody
	public void notifyUrl(HttpServletRequest request) {
		Map<String, String> params = new HashMap<String, String>();
		Enumeration enu = request.getParameterNames();
		while (enu.hasMoreElements()) {
			String paraName = (String) enu.nextElement();
			String valueStr = request.getParameter(paraName);
			System.out.println(paraName + " = " + valueStr);
			params.put(paraName, valueStr);
		}
		try {
			boolean flag = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, charset, signType);
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
	}
	@RequestMapping("/findTrade")
	@ResponseBody
	public Map<String, Object> findTrade(HttpServletRequest request,Integer id,Integer userId,Integer drId) {
		try {
			return packData(tradeService.findTrade(id, userId, drId));
		} catch (Exception e) {
			e.printStackTrace();
			return warnException(e);
		}
	}
}
